package com.raos.quartz.job2;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * Cron2Scheduler
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2021/10/01 21:52
 */
@Component
public class Cron2Scheduler {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    /**
     * 向容器中添加定时任务
     *
     * @param cron
     * @throws SchedulerException
     */
    public void scheduleJobs(String cron) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduleJob(scheduler, cron);
    }

    /**
     * 添加一个定时任务
     *
     * @param scheduler
     * @param cron
     * @throws SchedulerException
     */
    private void scheduleJob(Scheduler scheduler, String cron) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(Cron2Job.class)
                .withIdentity("cronJob", "jobGroup")
                .build();

        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "triggerGroup")
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

}

